#!/bin/bash

# 获取软件安装信息
extract_info() {
    local keyword=$1
    local keyword_lower=$(echo "$keyword" | tr '[:upper:]' '[:lower:]')

    while IFS= read -r line; do
        package=$(echo "$line" | awk '{print $1}')
        package_lower=$(echo "$package" | tr '[:upper:]' '[:lower:]')
        if [[ "$package_lower" == *"$keyword_lower"* ]]; then
            installed=$(echo "$line" | awk '{print $2}')
            nodes=$(echo "$line" | awk '{print $3}')
            master=$(echo "$line" | awk '{print $4}')

            echo "安装包名: $package"
            echo "是否安装标志: $installed"
            echo "需要安装的所有节点: $nodes"

            if [ -n "$master" ]; then
                echo "主节点（如果有）: $master"
            fi

            return 0
        fi
    done < "$PLAY_HOME/frames.txt"

    return 1
}

# 寻找指定的安装包，找到返回0，未找到返回1
find_package() {
    local package_name=$1
    local package_name_lower=$(echo "$package_name" | tr '[:upper:]' '[:lower:]')

    # 检查完整匹配
    if [[ -f "$PLAY_HOME/frames/$package_name" ]]; then
        echo "0"
        return
    fi

    # 检查部分匹配（不区分大小写）
    for file in "$PLAY_HOME/frames"/*; do
        local file_lower=$(echo "$file" | tr '[:upper:]' '[:lower:]')
        if [[ "$file_lower" == *"$package_name_lower"* ]]; then
            echo "0"
            return
        fi
    done

    echo "1"
}

# 添加软件包安装配置
config_package() {
    local package_name=$1
    local has_master=$2
    local package_name_lower=$(echo "$package_name" | tr '[:upper:]' '[:lower:]')

    # 查找安装包（不区分大小写）
    declare -a packages=()
    for file in "$PLAY_HOME/frames"/*; do
        local file_lower=$(echo "$file" | tr '[:upper:]' '[:lower:]')
        if [[ "$file_lower" == *"$package_name_lower"* ]]; then
            packages+=("$file")
        fi
    done

    # 输出匹配的安装包
    if (( ${#packages[@]} > 0 )); then
        echo "以下是与 $package_name 相关的安装包："
        echo "======================================="
        for i in "${!packages[@]}"; do
            echo "$((i+1)), ${packages[$i]}"
        done

        # 让用户选择使用哪个安装包
        read -p "请输入要使用的安装包序号: " package_index
        if ! [[ "$package_index" =~ ^[0-9]+$ ]] || (( package_index < 1 )) || (( package_index > ${#packages[@]} )); then
            echo "输入无效，请输入正确的数字。"
            return 1
        fi

        chosen_package=${packages[$((package_index-1))]}
        chosen_package_name=$(basename "$chosen_package")

        # 让用户输入需要安装的节点
        read -p "请输入需要安装到哪些节点，用逗号分隔: " nodes

        # 如果有主节点，则让用户输入主节点名称
        if [[ "$has_master" == "true" ]]; then
            read -p "请输入主节点名称(没有可直接回车): " master_node
        fi

        # 写入配置到文件中
        echo -e "\n$chosen_package_name true $nodes $master_node" >> "$PLAY_HOME/frames.txt"
    else
        echo "找不到与 $package_name 相关的安装包。"
        echo "请先使用playground add [软件包] 添加安装包"
        
        if [[ "$package_name" == "mysql" ]]; then
            download_mysql
        fi
        return 1
    fi

    echo "======================================="
    echo "配置信息已更新"
    echo "======================================="
    extract_info $package_name
    echo "======================================="
    echo "请使用playground update config分发配置文件"

    return 0
}

# 添加特殊软件包配置（不需要安装包的情况）
config_special_package() {
    local package_name=$1
    local has_master=$2
    
    # 让用户输入需要安装的节点
    read -p "请输入需要安装到哪些节点，用逗号分隔: " nodes
    
    # 如果有主节点，则让用户输入主节点名称
    local master_node=""
    if [[ "$has_master" == "true" ]]; then
        read -p "请输入主节点名称(没有可直接回车): " master_node
    fi
    
    # 写入配置到文件中
    echo -e "\n$package_name true $nodes $master_node" >> "$PLAY_HOME/frames.txt"
    
    echo "======================================="
    echo "配置信息已更新"
    echo "======================================="
    extract_info $package_name
    echo "======================================="
    echo "请使用playground update config分发配置文件"
    
    return 0
}

# 在线下载MySQL
download_mysql() {
    read -p "是否需要在线下载MySQL 5.7.37 版本？(y/n): " choice
    echo "======================================="
    case $choice in
        y|Y )
            mkdir $PLAY_HOME/frames/mysql-rpm-pack-5.7.37
            wget -P $PLAY_HOME/frames/mysql-rpm-pack-5.7.37 http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-community-server-5.7.37-1.el7.x86_64.rpm
            wget -P $PLAY_HOME/frames/mysql-rpm-pack-5.7.37 http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-community-client-5.7.37-1.el7.x86_64.rpm
            wget -P $PLAY_HOME/frames/mysql-rpm-pack-5.7.37 http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-community-libs-5.7.37-1.el7.x86_64.rpm
            wget -P $PLAY_HOME/frames/mysql-rpm-pack-5.7.37 http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-community-common-5.7.37-1.el7.x86_64.rpm
            wget -P $PLAY_HOME/frames/mysql-rpm-pack-5.7.37 http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-community-devel-5.7.23-1.el7.x86_64.rpm
            config_package mysql
            ;;
        * )
            echo "您可以使用离线方式准备安装包。"
            echo "======================================="
            echo "Mysql安装包需要放置在一个目录中，如mysql-rpm-pack-5.7.37"
            echo "在此目录中放置5个rpm包："
            echo "eg. mysql-community-server-5.7.37-1.el7.x86_64.rpm"
            echo "eg. mysql-community-client-5.7.37-1.el7.x86_64.rpm"
            echo "eg. mysql-community-libs-5.7.37-1.el7.x86_64.rpm"
            echo "eg. mysql-community-common-5.7.37-1.el7.x86_64.rpm"
            echo "eg. mysql-community-devel-5.7.23-1.el7.x86_64.rpm"
            echo "这些包可以在http://mirrors.sohu.com/mysql/中下载"
            echo "下载成功后请执行playground config mysql进行安装前配置"
            exit 0
            ;;
    esac
}

# 配置软件包安装入口-主方法
config() {
    local package_name=$1

    # 首先判断是否已经存在该软件包的配置信息
    if extract_info "$package_name"; then
        read -p "已经存在 $package_name 的安装信息，是否要更新？[y/n]: " answer
        case "$answer" in
            y|Y)
                # 如果用户需要更新，则删除旧的配置信息
                result=$(find_package $package_name)  # 调用 find_package 方法并保存结果

                if [ "$result" -eq "1" ]; then
                    echo "$package_name 安装包不存在。"
                    echo "请使用 'playground add [软件包]' 添加安装包。"
                    exit 1
                elif [ "$result" -eq "0" ]; then
                    sed -i "/$package_name/d" "$PLAY_HOME/frames.txt"
                    echo "已删除 $package_name 的旧配置信息。"
                    echo "======================================="
                else
                    echo "未知错误。"
                fi
                ;;
            *)
                # 如果用户不需要更新，则退出
                echo "未更新 $package_name 的配置信息。"
                return 0
                ;;
        esac
    else
        echo "目前没有关于 $package_name 的配置信息，请进行配置。"
        echo "======================================="
    fi

    # 调用config_package方法配置新的信息
    config_package "$package_name" true

}


if [ $1 == "config" ]; then 

    case $2 in 
        docker)
          config_special_package "docker" "false"
        ;;
        k8s)
          config_special_package "k8s" "true"
        ;;
        jdk)
          config "jdk"
        ;;
        scala)
          config "scala"
        ;;
        hadoop)
          config "hadoop"
        ;;
        es)
          config "elasticsearch"
        ;;
        mysql)
          config "mysql"
        ;;
        hive)
          config "hive"
        ;;
        tez)
          config "tez"
        ;;
        zeppelin)
          config "zeppelin"
        ;;
        flink)
          config "flink"
        ;;
        zookeeper)
          config "zookeeper"
        ;;
        kafka)
          config "kafka"
        ;;
        ds)
          config "dolphinscheduler"
        ;;
        spark)
          config "spark"
        ;;
        sqoop)
          config "sqoop"
        ;;
        clickhouse)
          config "clickhouse"
        ;;
        doris)
          config "doris"
        ;;
        starrocks)
          config "starrocks"
        ;;
        datax)
          config "datax"
        ;;
        hbase)
          config "hbase"
        ;;
        trino)
          config "trino"
          ;;
        neo4j)
          config "neo4j"
        ;;
        kyuubi)
          config "kyuubi"
        ;;
        *)
          echo "非法参数"
        ;;
    esac
        
elif [ $1 == "download" ]; then 

    case $2 in 
        mysql)
          download_mysql
        ;;
        *)
          echo "非法参数"
        ;;
    esac
        
fi